<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h1 class="login-title">系统登录</h1>
        <p class="login-subtitle">欢迎使用Vue Sound系统</p>
      </div>
      
      <div class="login-tabs">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="密码登录" name="password">
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              class="login-form"
              @submit.prevent="handlePasswordLogin"
            >
              <el-form-item prop="username">
                <el-input
                  v-model="passwordForm.username"
                  placeholder="请输入用户名"
                  size="large"
                  prefix-icon="User"
                  clearable
                />
              </el-form-item>
              
              <el-form-item prop="password">
                <el-input
                  v-model="passwordForm.password"
                  type="password"
                  placeholder="请输入密码"
                  size="large"
                  prefix-icon="Lock"
                  show-password
                  clearable
                  @keyup.enter="handlePasswordLogin"
                />
              </el-form-item>
              
              <el-form-item>
                <div class="login-options">
                  <el-checkbox v-model="passwordForm.remember">记住密码</el-checkbox>
                  <el-link type="primary" @click="handleForgotPassword">忘记密码？</el-link>
                </div>
              </el-form-item>
              
              <el-form-item>
                <el-button
                  type="primary"
                  size="large"
                  class="login-button"
                  :loading="passwordLoading"
                  @click="handlePasswordLogin"
                >
                  {{ passwordLoading ? '登录中...' : '登录' }}
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          
          <el-tab-pane label="扫码登录" name="qr">
            <div class="qr-login-container">
              <div class="qr-code-wrapper">
                <div v-if="qrLoading" class="qr-loading">
                  <el-icon class="is-loading"><Loading /></el-icon>
                  <p>生成二维码中...</p>
                </div>
                <div v-else-if="qrCodeUrl" class="qr-code">
                  <img :src="qrCodeUrl" alt="登录二维码" />
                  <p class="qr-tip">请使用手机扫描二维码登录</p>
                </div>
                <div v-else class="qr-error">
                  <el-icon><Warning /></el-icon>
                  <p>二维码生成失败</p>
                  <el-button type="primary" @click="generateQRCode">重新生成</el-button>
                </div>
              </div>
              
              <div class="qr-status">
                <el-alert
                  v-if="qrStatus"
                  :title="qrStatus.title"
                  :type="qrStatus.type"
                  :description="qrStatus.description"
                  show-icon
                  :closable="false"
                />
              </div>
              
              <div class="qr-actions">
                <el-button @click="generateQRCode" :loading="qrLoading">
                  <el-icon><Refresh /></el-icon>
                  刷新二维码
                </el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <div class="login-footer">
        <p class="copyright">© 2024 Vue Sound System. All rights reserved.</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading, Warning, Refresh } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

const router = useRouter()

// 响应式数据
const activeTab = ref('password')
const passwordLoading = ref(false)
const qrLoading = ref(false)
const qrCodeUrl = ref('')
const qrStatus = ref<{
  title: string
  type: 'success' | 'warning' | 'error' | 'info'
  description: string
} | null>(null)

// 密码登录表单
const passwordFormRef = ref<FormInstance>()
const passwordForm = reactive({
  username: '',
  password: '',
  remember: false
})

// 表单验证规则
const passwordRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 二维码轮询定时器
let qrPollingTimer: number | null = null
let qrToken = ''

// 处理标签页切换
const handleTabChange = (tabName: string) => {
  if (tabName === 'qr' && !qrCodeUrl.value) {
    generateQRCode()
  } else if (tabName === 'password') {
    stopQRPolling()
  }
}

// 密码登录
const handlePasswordLogin = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1500))
    // passwordForm.username === 'admin' && passwordForm.password === '123456'
    // 模拟登录验证
    if (passwordForm.username === 'admin' && passwordForm.password === '123456') {
      // 登录成功
      const userInfo = {
        id: 1,
        username: passwordForm.username,
        name: '管理员',
        avatar: '',
        loginTime: new Date().toISOString()
      }
      
      // 保存用户信息到localStorage
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      localStorage.setItem('isLoggedIn', 'true')
      
      ElMessage.success('登录成功！')
      
      // 跳转到首页
      router.push('/dashboard')
    } else {
      ElMessage.error('用户名或密码错误！')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error('登录失败，请重试')
  } finally {
    passwordLoading.value = false
  }
}

// 忘记密码
const handleForgotPassword = () => {
  ElMessageBox.alert('请联系系统管理员重置密码', '忘记密码', {
    confirmButtonText: '确定'
  })
}

// 生成二维码
const generateQRCode = async () => {
  qrLoading.value = true
  qrCodeUrl.value = ''
  qrStatus.value = null
  
  try {
    // 模拟生成二维码
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 生成随机token
    qrToken = Math.random().toString(36).substring(2, 15)
    
    // 模拟二维码URL（实际项目中这里应该是真实的二维码生成API）
    qrCodeUrl.value = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(JSON.stringify({
      type: 'login',
      token: qrToken,
      timestamp: Date.now()
    }))}`
    
    qrStatus.value = {
      title: '请扫描二维码',
      type: 'info',
      description: '使用手机扫描上方二维码完成登录'
    }
    
    // 开始轮询二维码状态
    startQRPolling()
    
  } catch (error) {
    console.error('生成二维码失败:', error)
    qrStatus.value = {
      title: '生成失败',
      type: 'error',
      description: '二维码生成失败，请重试'
    }
  } finally {
    qrLoading.value = false
  }
}

// 开始轮询二维码状态
const startQRPolling = () => {
  stopQRPolling() // 先停止之前的轮询
  
  qrPollingTimer = window.setInterval(async () => {
    try {
      // 模拟检查二维码状态
      const status = await checkQRStatus(qrToken)
      
      if (status === 'scanned') {
        qrStatus.value = {
          title: '已扫描',
          type: 'warning',
          description: '请在手机上确认登录'
        }
      } else if (status === 'confirmed') {
        // 登录成功
        const userInfo = {
          id: 2,
          username: 'mobile_user',
          name: '移动用户',
          avatar: '',
          loginTime: new Date().toISOString()
        }
        
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        localStorage.setItem('isLoggedIn', 'true')
        
        qrStatus.value = {
          title: '登录成功',
          type: 'success',
          description: '正在跳转...'
        }
        
        stopQRPolling()
        
        setTimeout(() => {
          router.push('/dashboard')
        }, 1000)
      } else if (status === 'expired') {
        qrStatus.value = {
          title: '二维码已过期',
          type: 'error',
          description: '请重新生成二维码'
        }
        stopQRPolling()
      }
    } catch (error) {
      console.error('检查二维码状态失败:', error)
    }
  }, 2000) // 每2秒检查一次
}

// 停止轮询
const stopQRPolling = () => {
  if (qrPollingTimer) {
    clearInterval(qrPollingTimer)
    qrPollingTimer = null
  }
}

// 检查二维码状态（模拟）
const checkQRStatus = async (token: string): Promise<'waiting' | 'scanned' | 'confirmed' | 'expired'> => {
  // 模拟API调用
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // 模拟不同的状态（实际项目中这里应该是真实的API调用）
  const random = Math.random()
  if (random < 0.1) return 'scanned'
  if (random < 0.15) return 'confirmed'
  if (random < 0.2) return 'expired'
  return 'waiting'
}

// 组件挂载时检查是否已登录
onMounted(() => {
  const isLoggedIn = localStorage.getItem('isLoggedIn')
  if (isLoggedIn === 'true') {
    router.push('/dashboard')
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopQRPolling()
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
  min-height: 500px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin: 0 0 8px 0;
}

.login-subtitle {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.login-tabs {
  margin-bottom: 20px;
}

.login-form {
  margin-top: 20px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
}

.qr-login-container {
  text-align: center;
  padding: 20px 0;
}

.qr-code-wrapper {
  margin-bottom: 20px;
}

.qr-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #666;
}

.qr-loading .el-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.qr-code {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.qr-code img {
  width: 200px;
  height: 200px;
  border: 1px solid #ddd;
  border-radius: 8px;
  margin-bottom: 10px;
}

.qr-tip {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.qr-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #f56c6c;
}

.qr-error .el-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.qr-status {
  margin-bottom: 20px;
}

.qr-actions {
  display: flex;
  justify-content: center;
}

.login-footer {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.copyright {
  color: #999;
  font-size: 12px;
  margin: 0;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-tabs__content) {
  padding-top: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-button) {
  border-radius: 8px;
}
</style>
